<template>
  <div style="padding-left:100px;">
    <el-form :model="oneList" :rules="rules" style="width:300px;margin-top:20px;" label-width="80px">
      <el-form-item label="姓名" prop="username">
        <el-input v-model="oneList.username" size="mini" />
      </el-form-item>
      <el-form-item label="工号" prop="workNumber">
        <el-input v-model="oneList.workNumber" size="mini" disabled />
      </el-form-item>
      <el-form-item label="手机" prop="mobile">
        <el-input v-model="oneList.mobile" size="mini" :disabled="isEdit" />
      </el-form-item>
      <el-form-item label="部门" prop="departmentId">
        <!-- <el-input v-model="oneList.departmentName" size="mini" /> -->
        <el-cascader v-model="oneList.departmentName" :options="departments" :props="{label:'name',value:'id'}" />
      </el-form-item>
      <el-form-item label="聘用形式" prop="formOfEmployment">
        <!-- <template #default="scope"> -->
        <el-select v-model="oneList.formOfEmployment">
          <el-option label="正式" :value="1" />
          <el-option label="非正式" :value="2" />
        </el-select>
        <!-- </template> -->

      </el-form-item>
      <el-form-item label="入职时间" prop="timeOfEntry">
        <el-date-picker
          v-model="oneList.timeOfEntry"
          type="date"
          placeholder="选择日期"
          clearable
        />
      </el-form-item>
      <el-form-item label="转正时间" prop="correctionTime">
        <el-date-picker
          v-model="oneList.correctionTime"

          type="date"
          placeholder="选择日期"
          clearable
        />
      </el-form-item>
      <el-form-item label="员工头像" prop="staffPhoto">
        <!-- <el-avatar :src="oneList.staffPhoto" /> -->
        <!-- 头像上传到第三方 -->
        <!-- action -->
        <el-upload
          class="avatar-uploader"
          action=""
          :before-upload="berforeUpload"
          :show-file-list="false"
          accept="image/png,image/jpg,image/jpeg,image/gif,image/webp"
        >
          <img v-if="oneList.staffPhoto" :src="oneList.staffPhoto" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" @click="update">更新</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getDepartments } from '@/api/department'
import { parseTime, transListToTree } from '@/utils'
import { oneemployee, addemployee, editemployee } from '@/api/employee'
// ------
// var COS = require('cos-js-sdk-v5');
import COS from 'cos-js-sdk-v5'

// SECRETID 和 SECRETKEY 请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
var cos = new COS({
  SecretId: 'AKIDdBXfzHLBmALI0RfhW3LRJzSpxq1yjHXY',
  SecretKey: 'vb3GF1CBxkMlzzoQnyviHciojQt8C2e1'
})
export default {
  data() {
    return {
      oneList: {},
      departments: [],
      rules: {
        username: [{ required: true, message: '请输入姓名', trigger: 'blur' }, {
          min: 1, max: 4, message: '姓名为1-4位'
        }],
        mobile: [{ required: true, message: '请输入手机号', trigger: 'blur' }, {
        //   pattern 正则表达式
          pattern: /^1[3-9]\d{9}$/,
          message: '手机号格式不正确',
          trigger: 'blur'
        }],
        formOfEmployment: [{ required: true, message: '请选择聘用形式', trigger: 'blur' }],
        departmentId: [{ required: true, message: '请选择部门', trigger: 'blur' }],
        timeOfEntry: [{ required: true, message: '请选择入职时间', trigger: 'blur' }],
        correctionTime: [{ required: true, message: '请选择转正时间', trigger: 'blur' }, {
          validator: (rule, value, callback) => {
            if (this.oneList.timeOfEntry) {
              if (new Date(this.oneList.timeOfEntry) > new Date(value)) {
                callback(new Error('转正时间不能小于入职时间'))
                return
              }
            }
            callback()
          }
        }]
      }
    }
  },
  computed: {
    isEdit() {
      // 返回true
      return !!this.$route.params.id
    }
  },
  async created() {
    await this.oneemployee()
    await this.getDepartments()
  },
  methods: {
    async oneemployee() {
      const id = this.$route.params.id
      if (!id) return
      //   console.log(id)
      const res = await oneemployee(id)
      //   console.log(res)
      this.oneList = res
    //   console.log(this.oneList)
    },
    async getDepartments() {
      const res = await getDepartments()
      this.departments = transListToTree(res, 0)
    },
    async update() {
      const obj = { ...this.oneList }
      obj.departmentId = obj.departmentName.slice(-1)[0]
      obj.timeOfEntry = parseTime(obj.timeOfEntry, '{y}-{m}-{d}')
      console.log(obj)
      if (this.isEdit) {
        // 修改
        await editemployee(obj)
      } else {
        // 新增
        await addemployee(obj)
      }
    },
    async  berforeUpload(file) {
      console.log(file)
      try {
        const res = await cos.uploadFile({
          Bucket: 'shadow-1319023616', /* 填写自己的 bucket，必须字段 */
          Region: 'ap-chengdu', /* 存储桶所在地域，必须字段 */
          Key: 'renzi' + +new Date() + file.name, /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
          Body: file, // 上传文件对象
          SliceSize: 1024 * 1024 * 5 /* 触发分块上传的阈值，超过5MB 使用分块上传，小于5MB使用简单上传。可自行设置，非必须 */
        })
        console.log(res)
        this.oneList.staffPhoto = 'http://' + res.Location
      } catch (e) {
        console.log(e)
      }
      return Promise.reject()
    }
  }
}
</script>

<style scoped lang='scss'>
::v-deep .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }</style>
